import 'dart:io';

import 'package:clipboard/clipboard.dart';
import 'package:file_picker/file_picker.dart';
import 'package:file_transfer/manager/webrtc_manager.dart';
import 'package:file_transfer/model/message_model.dart';
import 'package:file_transfer/model/simple_model.dart';
import 'package:file_transfer/pojo/channel_message.dart';
import 'package:file_transfer/pojo/message.dart';
import 'package:file_transfer/route/simple_route.dart';
import 'package:file_transfer/theme/colors.dart';
import 'package:file_transfer/utils/toast_util.dart';
import 'package:file_transfer/widget/message_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:provider/provider.dart';

class TransferFragment extends StatefulWidget {
  const TransferFragment({super.key});

  @override
  State<TransferFragment> createState() => _TransferFragmentState();
}

class _TransferFragmentState extends State<TransferFragment> with WidgetsBindingObserver{

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }


  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  final _textController = TextEditingController();

  _pasteText() async{
    final text = await FlutterClipboard.paste();
    _textController.text = text;
  }

  _sendMessage() async{
    final simpleModel = context.read<SimpleModel>();
    final messageModel = context.read<MessageModel>();
    if(!simpleModel.isLogin){
      debugPrint("请先登录");
      ToastUtil.show("请先登录");
      SimpleRoute.instance().toLoginPage(context);
      return;
    }

    if(_textController.text.isEmpty){
      debugPrint("请输入消息内容");
      ToastUtil.show("请输入消息内容");
      return;
    }

    final webrtcManager = WebrtcManager.instance(context);
    if(messageModel.selectAllClient){
      for (final value in messageModel.onlineUserList.map((e) => e.key)) {
        messageModel.client = User(key: value);
        await webrtcManager.sendChatMessage(_textController.text);
      }
      // 发送完消息，key会更新到最后一个，要持久化，每次发送完就重新设置为全局
      messageModel.selectAllClient = true;
    }else if (!messageModel.isRightKey()) {
      ToastUtil.show("请选择客户端");
      return;
    }else{
      webrtcManager.sendChatMessage(_textController.text);
    }
    _textController.clear();
  }

  Future<List<File>?> _getFile() async{
    try {
      final res = await FilePicker.platform.pickFiles(
          allowMultiple: true, // 选择多个文件
          type: FileType.any // 文件类型
      );
      if (res != null && res.files.isNotEmpty) {
        // 将文件转换为fileList
        return res.files.map((e) => File(e.path!)).toList();
      }
    } catch (e) {
      debugPrint("错误信息：$e");
      return null;
    }
    return null;
  }

  _sendFile() async {
    final simpleModel = context.read<SimpleModel>();
    final messageModel = context.read<MessageModel>();
    if (!simpleModel.isLogin) {
      debugPrint("请先登录");
      ToastUtil.show("请先登录");
      SimpleRoute.instance().toLoginPage(context);
      return;
    }

    if (!messageModel.isRightKey()) {
      ToastUtil.show("请选择客户端");
      return;
    }

    if(!messageModel.isSendNextFile){
      ToastUtil.show("请等待列表文件发送完成");
      return;
    }

    final webrtcManager = WebrtcManager.instance(context);
    final list = await _getFile();
    if (list == null) {
      return;
    }

    send() async{
      for (final file in list) {
        await webrtcManager.sendFile(file);
      }
    }

    if(messageModel.selectAllClient){
      for (final value in messageModel.onlineUserList.map((e) => e.key)) {
        messageModel.client = User(key: value);
        await send();
      }
      // 发送完消息，key会更新到最后一个，要持久化，每次发送完就重新设置为全局
      messageModel.selectAllClient = true;
    }else if (!messageModel.isRightKey()) {
      ToastUtil.show("请选择客户端");
      return;
    }else{
      await send();
    }

  }

  int _lastLen = 0;
  @override
  Widget build(BuildContext context) {
    final messageModel = context.watch<MessageModel>();
    SchedulerBinding.instance.addPostFrameCallback((_) {
      debugPrint("postFrame");
      if(_lastLen == messageModel.chatMessageList.length){
        return;
      }
      final controller = messageModel.channelMessageController;
      controller.animateTo(controller.position.maxScrollExtent,duration: const Duration(milliseconds: 200), curve: Curves.easeInOut);
      _lastLen = messageModel.chatMessageList.length;
    });
    return Column(
      children: [
        Expanded(
          child: Container(
          // color: Colors.blue,
          alignment: Alignment.center,
          child: ListView.builder(
              controller: messageModel.channelMessageController,
              itemCount: messageModel.chatMessageList.length,
              itemBuilder: (BuildContext context, int index) {
                final data = messageModel.chatMessageList[index];
                if(data is TextChannelMessage){
                  return TextMessageWidget(data);
                }else if(data is FileChannelMessage){
                  return FileMessageWidget(data);
                }else if(data is SystemMessage){
                  return Center(child: SystemMessageWidget(data));
                }
                return Center(child: Text(data.toString()));
              }),
        )),
        Container(
          margin: const EdgeInsets.only(bottom: 10),
          child: Column(
            children: [
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Expanded(
                      child: Container(
                        padding: const EdgeInsets.only(left: 8,right: 8,top: 0,bottom: 0),
                        decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(8.0)
                        ),
                        child: TextField(
                          minLines: 1,
                          maxLines: 3,
                          controller: _textController,
                          decoration: const InputDecoration(
                            border: InputBorder.none, // 设置边框为无
                            focusedBorder: InputBorder.none, // 设置聚焦时的边框为无
                            enabledBorder: InputBorder.none, // 设置启用时的边框为无
                            errorBorder: InputBorder.none, // 设置错误时的边框为无
                            disabledBorder: InputBorder.none, // 设置禁用时的边框为无
                          ),
                          style: const TextStyle(
                            fontSize: 20
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(width: 10),
                    InkWell(
                      onTap: _sendMessage,
                      child: Container(
                        decoration: BoxDecoration(
                          color: ThemeColors.btnBlue,
                          borderRadius: BorderRadius.circular(8.0),
                        ),
                        padding: const EdgeInsets.all(6.0),
                        child: const Icon(Icons.arrow_upward_sharp,size: 40,color: Colors.white,),
                      ),
                    )
                  ],
                ),
              ),
              Row(
                children: [
                  const SizedBox(width: 20,),
                  InkWell(
                      onTap: _pasteText,
                      child: const Icon(
                        Icons.paste,
                        size: 35,
                      )),
                  const SizedBox(width: 20,),
                  InkWell(
                      onTap: _sendFile,
                      child: const Icon(
                        Icons.file_present,
                        size: 35,
                      )),
                ],
              )
            ],
          ),
        ),
      ],
    );
  }
}
